# ID :VIrtualman 编写
import  pexpect
import  os
import datetime
import themain
def GetMemory(pid):
    pex2 = pexpect.spawn('/bin/bash', ['-c', 'ps -eo pid,size'])
    allstring = pex2.read().decode()
    lenstring = allstring.find(str(pid))
    # print(lenstring)
    # print(lenstring+len(str(pid)))
    input()
    memory = allstring[lenstring + len(str(pid)):lenstring + len(str(pid)) + 9]
    memory = int(memory)
    return memory

def Evaluation(code,lan,n,data_in,data_out,data_memory,data_time):
    file_name=""
    if lan=='1':
        bash_bianyi = 'gcc'
        file_name="./a.c"
    if lan=='2':
        bash_bianyi = 'g++'
        file_name="./a.cpp"
    fp = open(file_name, 'w')
    #print(file_name)
    fp.write(code)
    fp.close()
    open('res.txt', 'w')
    for i in range(0,len(data_in)):
        #print(data_out[i])

        inf_bianyi =os.system(bash_bianyi+' '+file_name)
        #print(inf_bianyi)
        if (inf_bianyi==0):
            pass;
        else:
            print("CE")
            ce=1
            #Return_Server_res("CE")
            return
        shell_cmd = './a.out >>res.txt'
        pex = pexpect.spawn('/bin/bash', ['-c', shell_cmd])

        start = datetime.datetime.now()
        themain.all_res_memory[i] =GetMemory(pex.pid)
        pex.sendline(data_in[i])

        #z = 0
        #while (1):
        #    z = z + 1
        #    if z == 150000000:
        #        break

        while(1):
            end = datetime.datetime.now()
            usetime = (end - start).microseconds / 1000+(end-start).seconds*1000
            themain.all_res_time[i] = usetime
            if(pex.isalive() and usetime>int(data_time)):
                themain.all_res[i] = "TLE"
                print("程序运行时间：" + str(usetime) + 'ms')
                pex.sendintr()
                print("TLE")
                break;
            if(pex.isalive()== False):
                break;
        try:
            if themain.all_res[i]=='TLE':
                continue;
        except:
            pass;
        if (themain.all_res_memory[i] > int(data_memory)):
            themain.all_res[i] = 'MLE'
            print("MLE")
            pex.sendintr()
            print("程序运行空间：" + themain.all_res_memory[i] + 'kb')
            continue
        #Return_Server_res("TLE")
        res=open('res.txt',"r").read()
        themain.all_res_time[i] = usetime
        print("程序运行空间："+str(themain.all_res_memory[i])+"B")
        print("程序运行时间："+str(themain.all_res_time[i])+'ms')
        print("用户答案："+res+" 标准答案："+data_out[i])
        pex.close()
        #os.popen2(data_out[i])

        if str(res).split()==data_out[i].split():
            print("AC")
            themain.all_res[i]='AC'
        else:

            print("WA")
            themain.all_res[i]='WA'
        #Return_Server_res(,all_res)
        os.remove('res.txt')
